package Firstdroid.Gps;
//import MainActivity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
//import com.google.android.maps.MapActivity;
//import com.google.android.maps.MapView;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import android.location.GpsStatus.NmeaListener;

/*When I wrote this, only God and I understood What I was doing! Now, God only knows! */
public class UrbanExplorer extends Service {
	static String NMEADATA;
	TextView output;
	
	@Override
	public IBinder onBind(Intent arg0) {
	return null;
	}
	
	@Override
	public void onCreate()
	{	
		super.onCreate();
	}
	@Override
	public void onStart(Intent intent, int startId) 
	{
		LocationManager LM = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        LocationListener LL = new MyLocationListener();
		LM.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, LL);
        LM.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, LL);
        LM.addNmeaListener(new NmeaListener() {
        public void onNmeaReceived(long timestamp, String nmea) 
        { 
            	nmea.trim();
            	nmea=nmea.replaceAll("\r\n","");
            	nmea=nmea.replaceAll("\\s", "");
            	String[] sentences = nmea.split("\n");
            	for(int i=0; i<sentences.length; i++)
             	{
            	if(sentences[i].contains("$GPRMC") || sentences[i].contains("$GPGGA") || sentences[i].contains("$GPGSA")|| sentences[i].contains("$GPGSV"))
            	            {
            	                NMEADATA=sentences[i]+"|";
            	            }
            	Log.d("inside", NMEADATA);
            	}	
        }});
	}
	@Override
	public void onDestroy() {
		//LocationManager.removeUpdates(LL);
		//super.onStop();
		System.exit(0);
		//super.onDestroy();
		Toast.makeText(this, "UrbanExplorer Stopped", Toast.LENGTH_LONG).show();      
		}
	/* Class My Location Listener */
    public class MyLocationListener implements LocationListener
    {
    	public void onLocationChanged(Location loc)
    	{
    		loc.getLatitude();
    		loc.getLongitude();
    		String Text = "You can find him at : " + "Latitude = " + loc.getLatitude() + " Longitude = "  + loc.getLongitude();
    		Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_LONG).show();
    		Toast.makeText( getApplicationContext(), NMEADATA, Toast.LENGTH_LONG).show();
    		//String url = "http://129.215.84.138:80/xampp/NMEAserver.php?nmeadata1="+NMEADATA;
    		//String url = "http://62.30.167.145:80/xampp/NMEAserver.php?nmeadata1="+NMEADATA;
    		TelephonyManager tMgr =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    		String MobileNumber = tMgr.getLine1Number();
    		NMEADATA = MobileNumber +"|"+NMEADATA;
    		Toast.makeText( getApplicationContext(), NMEADATA, Toast.LENGTH_LONG).show();
    		try{
    		String url = "http://xweb.geos.ed.ac.uk/~s1051713/cgi_bin/project/Server.php?DATA="+NMEADATA;
    		//String url = "http://localhost:8080/Server.php?nmeadata1="+NMEADATA;
    		HttpClient client = new DefaultHttpClient();
    		HttpGet httpget = new HttpGet(url);
            Toast.makeText( getApplicationContext(), url, Toast.LENGTH_LONG).show();
            
            try {
               	/*Toast.makeText( getApplicationContext(), "trying", Toast.LENGTH_LONG).show();
            	Log.d("inside", "firing request...");*/
                HttpResponse httpResponse = client.execute(httpget);
                Log.d("inside", "request sent" + httpResponse.getStatusLine().getStatusCode());
                /*Toast.makeText( getApplicationContext(), "done", Toast.LENGTH_LONG).show();
                String responseBody = EntityUtils.toString(httpResponse.getEntity());
                Log.d("a",responseBody);*/
                /*try {
        		    File root = Environment.getExternalStorageDirectory();
        		    if (root.canWrite()){
        		        File nmeafile = new File(root, "NMEAFILE.nmea");
        		        FileWriter nmeawriter = new FileWriter(nmeafile);
        		        BufferedWriter out = new BufferedWriter(nmeawriter);
        		        out.write(NMEADATA);
        		        out.write("\n");
        		        out.flush();
        		        out.close();
        		    }}
        		    catch (Exception e) {
                		// TODO Auto-generated catch block
                		e.printStackTrace();
                		} */
        		} 
            catch (Exception e) {
        		// TODO Auto-generated catch block
        		e.printStackTrace();
        		} 
        	/*
        	catch (IOException e) {
        		// TODO Auto-generated catch block
        		e.printStackTrace();
        		}	*/
    		}catch(IllegalArgumentException e)
    		{}	
        }
    public void onProviderDisabled(String provider) 
    	{
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_LONG ).show();
        }
    public void onProviderEnabled(String provider)
        {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_LONG ).show();
        }
    public void onStatusChanged(String provider, int status, Bundle extras)
        {
        	
        }    
    }/* End of Class MyLocationListener */
    
	
}   /* End of Class UrbanExplorer */